//index.js
import { Home } from 'home-model.js'
import SafeRenderUtil from '../../utils/saveRender.js'
var home = new Home();
//获取应用实例
const app = getApp()

Page({
  data: {
    rate: [],
    sort: [{ id: "1", name: "价格从高到低" }, { id: "2", name: "价格从低到高" }],
    size: [],
    bannerImg:'https://goods.dingdian.xin/FjoF9xq0raS763Gfi5DR4ae2CQ7P',
    closeBanner: false,
    productList: [], //产品列表
    loadingHidden: false,
    newWorkTimeOut:false,
    goodsListParames: {
      condition: "1",
      orderby: "1",
      categoryId: "",
      sizeCondition: "",
      rateCondition: ""
    },
    goodsPage: 1,
    goodsSize: 10,
    hasMore: false, //是否可以翻页
    dropDown: {
      showDisDown: true, //显示折扣下拉
      showSizeDown: true, //显示尺寸下拉
      showSortDown: true, //显示排序下拉
    },
    dropShade: false,
    rateCondition: { "全部": "", "1-2折": "1", "3-4折": "2", "5-6折": "3", "7-8折": "4" },
    sizeCondition: { "全部": "", "XXS": "1", "XS": "2", "S": "3", "M": "4", "L": "5", "XL": "6", "XXL": "7" },
    filterName: [],
    filterName2: [],
    hideFilter: true, //是否显示筛选页面
    isShowPopup: false, //是否显示弹窗
    tip: "",//弹窗显示内容
    categoryCount: null, //筛选选择条件共有商品数量
    scroll_height:false,
    checkDisable: true //查看按钮

  },
  onLoad: function (options) {
    app.aldstat.sendEvent('店铺首页');
    console.log("options.storeNo===================", options.storeNo, "options.scene==============", options.scene);
     wx.showLoading({
      title: '加载中...',
    })
    /*
    * 如果登录
    * 判断（分享进入,扫码进入）与当前用户比较，若不同退出登录
    * 同时放入缓存storeNo
    */

    let storeNo = wx.getStorageSync('userInfo').storeNo || wx.getStorageSync('storeNo') || "S00000001";

    console.log("storeNo----------------", storeNo);

    wx.setStorageSync('storeNo', storeNo);
    //分享进店
    if (options && options.storeNo) {

      storeNo = options.storeNo;
      wx.setStorageSync('storeNo', storeNo);
      let userInfo = wx.getStorageSync('userInfo');

      //判断当前用户storeNo是否与连接storeNo相同
      if (userInfo) {
        if (userInfo.storeNo !== storeNo) {
          wx.removeStorageSync('userInfo')
        }
      }
    }

    //扫码进店
    if (options && options.scene) {
      var scene = decodeURIComponent(options.scene);
      if (scene != 'undefined' && scene != null) {
        app.aldstat.sendEvent('扫码进店');
        var sceneList = scene.split(',');
        storeNo = sceneList[0];
        wx.setStorageSync('storeNo', storeNo);
        // this.data.employeNo = sceneList[1];
        let userInfo = wx.getStorageSync('userInfo');

        //判断当前用户storeNo是否与连接storeNo相同
        if (userInfo) {
          if (userInfo.storeNo !== storeNo) {
            wx.removeStorageSync('userInfo')
          }
        }
      }
    }
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({
      storeNo,
      userInfo
    })

    let that = this;

    /**
      * 根据storeNo判断用户是否登录以及选择门店
      */

   
    if (storeNo) {

      //获取用户权限
      that._getAuthorize(() => {
        that._loadData(); //页面加载数据
      });
    } else {
      console.log("没有店铺编号!");
    }
  },
  onShow() {
    wx.setStorageSync('loginClose', false);

    // 如果登录
    let that = this;
    let userStoreNo = wx.getStorageSync('userInfo').storeNo;
    if (userStoreNo) {
      if (this.data.storeNo != userStoreNo) {
        var storeNo = wx.getStorageSync('userInfo').storeNo;
        this.setData({
          storeNo,
          closeBanner:false
        });
        that._loadData(); //页面加载数据
      }
      that.getCart(); //计算购物车数量
    }

  },
  _loadData(cb) {

    // 页面数据加载
    let that = this;

    // 定义数据数组
    this.render = new SafeRenderUtil({
      arrName: 'productList',
      setData: this.setData.bind(this)
    });
    this.setData({
      filterName: [],
      goodsCategory: [],
      "goodsListParames.categoryId": "",
      "goodsListParames.sizeCondition": "",
      "goodsListParames.rateCondition": "",
      closeBanner:false
    });

    //筛选列表加载
    this.getCondition();
    this._getGoodsCategory("0", 1);

    // 加载商品列表
    this.getStockGoodsList();
    cb && cb();
    this.getCart();

    wx.hideLoading();
  },

  //门店商品列表
  getStockGoodsList() {

    let that = this;
    let parames = {
      "page": that.data.goodsPage,
      "size": that.data.goodsSize,
      "storeNo": that.data.storeNo
    }, { goodsListParames } = this.data;
    Object.assign(parames, goodsListParames);
    console.log("parames===================", parames);
    if (parames.categoryId == "") {
      delete parames["categoryId"];
    }
    if (parames.sizeCondition == "") {
      delete parames["sizeCondition"];
    }
    if (parames.rateCondition == "") {
      delete parames["rateCondition"];
    }

    var { goodsPage, goodsSize } = this.data;

    home.getStockGoodsList(parames, res => {
      if (res.status) {
        that.setData({
          hasMore: true,
          loadingHidden: true,
          newWorkTimeOut: false
        });

        if (goodsPage + 1 > Math.ceil(res.total / goodsSize)) {
          that.setData({
            hasMore: false
          });
        }

        let data = res.data.length > 0 ? res.data : [];
        this.render.addList(data);


      }else{
        that.setData({
          hasMore: false,
          newWorkTimeOut:true
        });
        
      }
      wx.hideLoading();
      console.log("productList==========================", that.data.productList);
    })
  },
  //筛选条件加载
  getCondition() {
    let that = this;
    let storeNo = this.data.storeNo || wx.getStorageSync("storeNo");
    let parames = {
      "storeNo": storeNo,
      loadingHidden: true
    }
   
    //门店折扣条件列表
    home.getRateCondition(parames, res => {
      if (res.status) {
        if (res.data.length > 0) {
          res.data[0].selected = true;
          that.setData({
            rate: res.data,
           
            // rateData: res.data[0]
          })
        }
      }

    });

    //门店尺码条件列表
    home.getSizeCondition(parames, res => {
      if (res.status) {
        if (res.data.length > 0) {
          res.data[0].selected = true;
          that.setData({
            size: res.data,
            // sizeData: res.data[0]
          })
        }
      }
    });
  },

  //获取购物车数据
  getCart() {
    let that = this;
    let { storeNo } = this.data;
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      let parames = {
        "userId": '' + userInfo.id,
        "storeNo": '' + storeNo
      }
      home.getCart(parames, res => {
        if (res.status) {
          let total = 0;
          res.data.forEach((value, index) => {
            total += parseInt(value.goodsNum);
          })

          //设置购物车右上角红色点
          wx.setTabBarBadge({
            index: 1,
            text: '' + total,
          })

        }
      })
    }

  },

  //筛选按钮点击事件
  onFilterTap(e) {
    let that = this;
    let index = home.getDataSet(e, "index")
    let sectionIndex = home.getDataSet(e, "section");
    let categoryId = home.getDataSet(e, "categoryid");
    let item = "section" + sectionIndex;
    let { filterName } = this.data;

    let filterNameLen = this.data.filterName.length; //清空之前选项
    if (filterNameLen - sectionIndex > 0) {
      filterName.length = sectionIndex;
      that.setData({
        filterName: filterName
      })
    }

    that.data.goodsCategory[item].forEach((value, order) => {
      if (order == index) {
        value.checked = true;
        let itemName = "filterName[" + (sectionIndex - 1) + "].name";
        let itemId = "filterName[" + (sectionIndex - 1) + "].id";
        that.setData({
          [itemName]: value.categoryName,
          [itemId]: value.categoryId
        })
      } else {
        value.checked = false;
      }
    });
    let goodsCategory = that.data.goodsCategory;

    //设置样式
    that.setData({
      goodsCategory
    });

    //数据加载
    if (sectionIndex == "1") {
      that._getGoodsCategory("" + categoryId + "", 2, () => {
        let sectionP2 = "goodsCategory.section3"
        that.setData({
          [sectionP2]: [],
          categoryCount: null,
          checkDisable: true
        })
      });
    } else if (sectionIndex == "2") {
      that._getGoodsCategory("" + categoryId + "", 3, () => {
        that.setData({
          categoryCount: null,
          checkDisable: true
        })
      });
    } else if (sectionIndex == "3") {
      that.setData({
        checkDisable: false
      })

      //当点击最后一个元素时,统计产品数量
      that.getGoodsCategoryCount(categoryId);
    }

  },

  //清空筛选条件
  emptyFilte() {
    this.setData({
      filterName: [],
      goodsCategory: []
    });
    this.checkGoodList(cb);
    this._getGoodsCategory("0", 1); //重新加载弹窗内筛选条件
  },

  //重置
  resetList() {
    let that = this;
    this.setData({
      filterName: [],
      filterName2: [],
      goodsCategory: [],
      categoryCount: null,
      checkDisable: true,
      resetData:true//判断是否点击重置
    });
    this._getGoodsCategory("0", 1); //重新加载弹窗内筛选条件

  },

  //获取分类信息
  _getGoodsCategory(categoryPid, index, cb = () => { }) {
    let that = this;
    let parames = {
      "categoryPid": categoryPid
    };
    home.getGoodsCategory(parames, res => {
      if (res.status) {
        let goodsCategory = res.data;
        let section = "goodsCategory.section" + index + "";
        that.setData({
          [section]: goodsCategory
        });
        cb(); //执行完事件
      }
    });
  },

  //统计产品数量
  getGoodsCategoryCount(categoryId) {
    let that = this;
    let parames = {
      "categoryId": "" + categoryId + ""
    };
    home.getGoodsCategoryCount(parames, res => {

      if (res.status) {
        console.log(res.data);
        that.setData({
          categoryCount: res.data
        })
      }

    });
  },

  //获取用户权限设置
  _getAuthorize(callback) {
    var that = this;
    var userInfo = this.data.userInfo;
    if (!userInfo) {
      app.getUserSetting(res => { // 获取用户权限设置
        callback && callback();
      });
    } else {
      callback && callback();
    }
  },

  //跳转到商品详情页面
  onProductDetail(e) {
    let id = home.getDataSet(e, "id");
    let storeNo = this.data.storeNo;
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      wx.navigateTo({
        url: "/pages/product/product?id=" + id + "&storeNo=" + storeNo
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    }
  },

  //筛选横条菜单点击事件
  onDropTap: function (e) {
    let dropVal = home.getDataSet(e, "drop");
    let { dropDown } = this.data;
    let status = dropDown[dropVal] ? false : true;
    for (let i in dropDown) {
      if (i == dropVal) {
        dropDown[i] = status;
      } else {
        dropDown[i] = true;
      }

    }

    this.setData({
      dropDown,
      dropShade: !status
    });
  },

  //关闭所有筛选下拉框
  closeDropTap: function (e) {
    let { dropDown } = this.data;
    for (let i in dropDown) {
      dropDown[i] = true;
    }
    this.setData({
      dropDown,
      dropShade: false
    });
  },
  onSelectDrop(e) {
    let that = this,
      tapName = home.getDataSet(e, "tapname"),
      index = home.getDataSet(e, "index"),
      item = "tapName[" + index + "].selected",
      oldTabName = this.data[tapName],
      { rateCondition, sizeCondition } = that.data;
    
    //样式添加
    oldTabName.forEach((value, order) => {
      if (order != index) {
        value.selected = false;
      } else {
        value.selected = true;
      }
    });

    let tapData = tapName + 'Data'; //选中展示数据

    //遍历获取选中数据
    let value = this.data[tapName].filter((value, order) => {
      return order == index;
    })
    this.render.clearArr();
    this.setData({
      [tapName]: oldTabName,
      [tapData]: value[0],
      goodsPage: 1
    });

    //获取商品列表
    switch (tapName) {
      case "rate":
        let rate = that.data.rateData.rate_name;
        let rateValue = rateCondition[rate];
        that.setData({
          "goodsListParames.rateCondition": rateValue
        });
        break;
      case "size":
        let size = that.data.sizeData.size_name;
        let sizeValue = sizeCondition[size];
        that.setData({
          "goodsListParames.sizeCondition": sizeValue
        });
        break;
      case "sort":
        let sort = that.data.sortData.id;
        that.setData({
          "goodsListParames.condition": "2",
          "goodsListParames.orderby": "" + sort
        });
        break;
    }
    that.getStockGoodsList();
  },

  //筛选，查看商品列表
  checkGoodList() {
    wx.showLoading({
      title: '加载中...',
    })
    let { filterName } = this.data;
    let filterNameLen = filterName.length;
    console.log("filterName=========", filterName);
    let id = "";
    if (filterNameLen > 0) {
      id = filterName[filterNameLen - 1].id;
    } else {
      id = "";
    }

    this.render.clearArr();
    this.setData({
      "goodsListParames.categoryId": id.toString(),
      hideFilter: true,
      filterName2: filterName,
      goodsPage:1
    })

    this.getStockGoodsList();

  },
  onFilter(e) {
    this.setData({
      hideFilter: this.data.hideFilter ? false : true
    })

    //显示筛选条件时
    if (!this.data.hideFilter){
      this.setData({
        resetData: false //关闭点击重置按钮标识
      })
    }

    if (this.data.hideFilter && !this.data.checkDisable) {
      this.checkGoodList() //查询筛选条件
    }else if (this.data.resetData){
      this.checkGoodList()   //点击重置，需要查询
    }
  },
  //关闭banner
  oncloseBanner: function () {
    this.setData({
      closeBanner: true
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */

  onPullDownRefresh: function () {
    wx.showNavigationBarLoading(); //在标题栏中显示加载图标
    this.setData({
      goodsPage: 1,
      rateData: null,
      sizeData: null,
      sortData: null,
      checkDisable: true,
      filterName2: []
    });
    this._loadData(() => {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh(); //停止下拉刷新 
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */

  onReachBottom: function () {
    var { goodsPage, hasMore } = this.data;

    /**
     * 此处加上数据大小的判断
     */

    if (hasMore) {
      this.setData({
        goodsPage: goodsPage + 1
      })
      this.getStockGoodsList();
    }

  },
  /**
   * 用户点击右上角分享
   */

  onShareAppMessage: function () {
    app.aldstat.sendEvent('首页-分享');

    var { storeNo } = this.data;
    wx.showShareMenu({
      withShareTicket: true
    });
    console.log("storeNo----------------", storeNo);
    return {
      title: "一线品牌一折起的内购会",//storeInfo.brandName,
      path: '/pages/poster/poster?storeNo=' + storeNo,
      imageUrl: "https://goods.dingdian.xin/Fn0HqBuJWnh6DPBkRrwODgmhE4RJ",
      success: res => {
        if (res.shareTickets) {
          console.log(res.shareTickets);
          wx.getShareInfo({
            shareTicket: res.shareTickets[0],
            success: d => {
              console.log(d);
            }
          })
        }
      }
    }
  },
  onPageScroll: function (e) {
    var that = this;
    let closeBanner = this.data.closeBanner;
    let scrollTop = e.scrollTop;
    let topHeight = wx.getSystemInfoSync().windowWidth * 0.4 ;
    if (!closeBanner) {
      if (scrollTop >= topHeight - 2) {
        if (!this.data.scroll_height) {
          that.setData({
            ["scroll_height"]: true
          })
        }
      } else {
        if (this.data.scroll_height) {
          that.setData({
            ["scroll_height"]: false
          })
        }
      }
    }
  },
  scroll(e) {
    var that = this;
    let closeBanner = this.data.closeBanner;
    let scrollTop = e.detail.scrollTop;
    console.log("scrollTop================",scrollTop,e);
    let topHeight = wx.getSystemInfoSync().windowWidth * 0.4 + 82;

    console.log("topHeight================", topHeight);
    if (!closeBanner) {
      if (scrollTop >= topHeight) {
        if (!this.data.scroll_height){
          that.setData({
            ["scroll_height"]: true
          })
        }
      }else{
        if (this.data.scroll_height) {
          that.setData({
            ["scroll_height"]: false
          })
        }
        
      }
    }
    console.log("scroll_height===========", this.data.scroll_height)
  },
  scrolltolower: function () {
    var { goodsPage, hasMore } = this.data;

    /**
     * 此处加上数据大小的判断
     */

    if (hasMore) {
      this.setData({
        goodsPage: goodsPage + 1
      })
      this.getStockGoodsList();
    }

  },
  scrolltoupper: function () {
    console.log('触发了-----------------------scrolltoupper');
    if (this.data.scroll_height) {
      this.setData({
        ["scroll_height"]: false
      })
    }
  },
//   搜索跳转
  search(){
      wx.navigateTo({
          url: '/pages/search/search',
      })
  }
})
